package com.ztomorrow.ying_cun_plus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookInfoMapper;
import com.ztomorrow.ying_cun_plus.dao.po.BookInfo;
import com.ztomorrow.ying_cun_plus.dto.req.BookSearchReqDto;
import com.ztomorrow.ying_cun_plus.dto.resp.BookInfoRespDto;
import com.ztomorrow.ying_cun_plus.dto.resp.PageRespDto;
import com.ztomorrow.ying_cun_plus.dto.resp.RestResp;
import com.ztomorrow.ying_cun_plus.service.SearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;



//@Service
@RequiredArgsConstructor
public class DbSearchServiceImpl implements SearchService {

    private final BookInfoMapper bookInfoMapper;

    @Override
    public RestResp<PageRespDto<BookInfoRespDto>> searchBooks(BookSearchReqDto condition) {
        Page<BookInfo> page = new LambdaQueryChainWrapper<>(bookInfoMapper)
                .gt(BookInfo::getWordCount, 0)
                .and(!StrUtil.isEmptyIfStr(condition.getKeyword()),
                        i -> i.like(BookInfo::getBookName, condition.getKeyword())
                        .or().like(BookInfo::getAuthorName, condition.getKeyword()))
                .eq(condition.getWorkDirection() != null,
                        BookInfo::getWorkDirection, condition.getWorkDirection())
                .eq(condition.getCategoryId() != null,
                        BookInfo::getCategoryId, condition.getCategoryId())
                .eq(condition.getIsVip() != null,
                        BookInfo::getIsVip, condition.getIsVip())
                .eq(condition.getBookStatus() != null,
                        BookInfo::getBookStatus, condition.getBookStatus())
                .ge(condition.getWordCountMin() != null,
                        BookInfo::getWordCount, condition.getWordCountMin())
                .lt(condition.getWordCountMax() != null,
                        BookInfo::getWordCount, condition.getWordCountMax())
                .ge(condition.getUpdateTimeMin() != null,
                        BookInfo::getLastChapterUpdateTime, condition.getUpdateTimeMin())
                .last(condition.getSort() !=null, "order by " + condition.getSort())
                .page(new Page<>(condition.getPageNum(), condition.getPageSize()));

        return RestResp.ok(
                PageRespDto.of(condition.getPageNum(), condition.getPageSize(), page.getTotal(),
                        BeanUtil.copyToList(page.getRecords(), BookInfoRespDto.class)));

    }
}
